const { prisma } = require('../config/prisma');

/**
 * 创建测试用户脚本
 * 用于在没有微信小程序ID的情况下创建测试用户进行功能测试
 */
async function createTestUser() {
  try {
    console.log('🚀 开始创建测试用户...');

    // 测试用户数据
    const testUserData = {
      openid: 'test_openid_12345',
      nickname: '测试用户',
      avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
      phone_number: null,
      status: 'inactive', // 设置为未激活状态，用于测试购买后激活
      publishing_credits: 0, // 初始发布额度为0
      inviter_id: null
    };

    // 检查是否已存在测试用户
    const existingUser = await prisma.users.findUnique({
      where: { openid: testUserData.openid }
    });

    if (existingUser) {
      console.log('⚠️ 测试用户已存在，更新用户信息...');
      
      // 更新现有测试用户
      const updatedUser = await prisma.users.update({
        where: { openid: testUserData.openid },
        data: {
          nickname: testUserData.nickname,
          avatar_url: testUserData.avatar_url,
          status: testUserData.status,
          publishing_credits: testUserData.publishing_credits
        }
      });

      console.log('✅ 测试用户更新成功:');
      console.log(`   用户ID: ${updatedUser.id}`);
      console.log(`   OpenID: ${updatedUser.openid}`);
      console.log(`   昵称: ${updatedUser.nickname}`);
      console.log(`   状态: ${updatedUser.status}`);
      console.log(`   发布额度: ${updatedUser.publishing_credits}`);
      
      return updatedUser;
    } else {
      // 创建新的测试用户
      const newUser = await prisma.users.create({
        data: testUserData
      });

      console.log('✅ 测试用户创建成功:');
      console.log(`   用户ID: ${newUser.id}`);
      console.log(`   OpenID: ${newUser.openid}`);
      console.log(`   昵称: ${newUser.nickname}`);
      console.log(`   状态: ${newUser.status}`);
      console.log(`   发布额度: ${newUser.publishing_credits}`);
      
      return newUser;
    }

  } catch (error) {
    console.error('❌ 创建测试用户失败:', error);
    throw error;
  }
}

/**
 * 删除测试用户
 */
async function deleteTestUser() {
  try {
    console.log('🗑️ 开始删除测试用户...');

    const result = await prisma.users.delete({
      where: { openid: 'test_openid_12345' }
    });

    console.log('✅ 测试用户删除成功');
    return result;

  } catch (error) {
    if (error.code === 'P2025') {
      console.log('⚠️ 测试用户不存在，无需删除');
    } else {
      console.error('❌ 删除测试用户失败:', error);
      throw error;
    }
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const action = process.argv[2];
  
  if (action === 'delete') {
    deleteTestUser()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  } else {
    createTestUser()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  }
}

module.exports = {
  createTestUser,
  deleteTestUser
};
